﻿using Domain.NHibernate.Mappings;
using Domain.NHibernate.Models;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate;
using NHibernate.Cfg;

namespace Web.Logic.Models.UnitOfWorkClasses
{
    public class UnitOfWorkFactory : IUnitOfWorkFactory
    {
        private ISessionFactory sessionFactory;

        public ISession CurrentSession { get; private set; }

        public Configuration Configuration { get; private set; }



        private ISessionFactory SessionFactory
        {
            get { return sessionFactory ?? (sessionFactory = Configuration.BuildSessionFactory()); }
        }

        public UnitOfWorkFactory()
        {
            Configure();
        }

        public IUnitOfWork Create()
        {
            CurrentSession = SessionFactory.OpenSession();
            CurrentSession.FlushMode = FlushMode.Commit;

            return new UnitOfWork(CurrentSession);
        }

        public void Configure()
        {
            Configuration = Fluently.Configure().
                Database(
                    MsSqlConfiguration
                        .MsSql2008
                        .ConnectionString(x => x.FromConnectionStringWithKey("ApplicationServices"))
                        .UseReflectionOptimizer()
                )
                .Mappings(m => m.FluentMappings.AddFromAssemblyOf<DoerMap>())
                .BuildConfiguration();
        }

        public ISession ReturnSession()
        {
            return CurrentSession;
        }
    }
}